import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@WebServlet("/showrequest")
public class ShowRequest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        StringBuilder result = new StringBuilder();
        /*返回请求协议的名称和版本*/
        result.append(req.getProtocol());
        result.append("<br>");
        /*返回请求的HTTP方法的名称*/
        result.append(req.getMethod());
        result.append("<br>");
        /*从协议名称到HTTP请求的第一行查询字符串中，返回该请求的URL的一部分*/
        result.append(req.getRequestURI());
        result.append("<br>");
        /*返回包含在路径后的请求URL中的查询字符串*/
        result.append(req.getQueryString());
        result.append("<br>");
        /*返回指示请求上下文的请求URI部分*/
        result.append(req.getContextPath());
        result.append("<br>");

        result.append("=========================<br>");

        /*返回一个枚举，包含在该请求中包含的所有头名*/
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            /*getHeader方法：以字符串形式返回指定的请求头中的值*/
            String headerValue = req.getHeader(headerName);
            result.append(headerName + ": " + headerValue + "<br>");
        }

        // 在响应中设置上 body 的类型. 方便浏览器进行解析
        resp.setContentType("text/html;charset=utf8");
        resp.getWriter().write(result.toString());
    }
}
